package org.jeecgframework.core.util;

import java.io.PrintWriter;
import java.io.StringWriter;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

/**
 * Exception工具类
 * 
 * @author 张代浩
 */
/*
 * @author edit by XYQ
 * 
 * @date 20180312
 */
@ControllerAdvice
public class ExceptionUtil {

	/**
	 * 返回错误信息字符串
	 * 
	 * @param ex
	 *            Exception
	 * @return 错误信息字符串
	 */
	public static String getExceptionMessage(Exception ex) {
		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw);
		ex.printStackTrace(pw);
		return sw.toString();
	}

	// 运行时异常：RuntimeException
	@ExceptionHandler({ RuntimeException.class })
	public ModelAndView getExceptionMessage_RuntimeException(Exception ex) {
		ModelAndView mv = new ModelAndView("error");
		mv.addObject("eMessage", "运行时异常:" + ex);
		return mv;
	}

	// 空指针异常：NullPointerException
	@ExceptionHandler({ NullPointerException.class })
	public ModelAndView getExceptionMessage_NullPointerException(Exception ex) {
		ModelAndView mv = new ModelAndView("error");
		mv.addObject("eMessage", "空指针异常:" + ex);
		return mv;
	}

	// 算术异常： ArithmeticException
	@ExceptionHandler({ ArithmeticException.class })
	public ModelAndView getExceptionMessage_ArithmeticException(Exception ex) {
		ModelAndView mv = new ModelAndView("error");
		mv.addObject("eMessage", "算术异常:" + ex);
		return mv;
	}
	//类型强制转换异常：ClassCastException
	@ExceptionHandler({ ClassCastException.class })
	public ModelAndView getExceptionMessage_ClassCastException(Exception ex) {
		ModelAndView mv = new ModelAndView("error");
		mv.addObject("eMessage", "类型强制转换异常:" + ex);
		return mv;
	}
/*	//数组负下标异常：NegativeArrayException
	@ExceptionHandler({ NegativeArrayException.class })
	public ModelAndView getExceptionMessage_NegativeArrayException(Exception ex) {
		ModelAndView mv = new ModelAndView("error");
		mv.addObject("eMessage", "类型强制转换异常:" + ex);
		return mv;
	}*/
	//数组下标越界异常：ArrayIndexOutOfBoundsException
	@ExceptionHandler({ ArrayIndexOutOfBoundsException.class })
	public ModelAndView getExceptionMessage_ArrayIndexOutOfBoundsException(Exception ex) {
		ModelAndView mv = new ModelAndView("error");
		mv.addObject("eMessage", "数组下标越界异常:" + ex);
		return mv;
	}
}